package com.yuzhenxin.bookstore.dao;

import com.yuzhenxin.bookstore.domain.User;
import com.yuzhenxin.bookstore.tools.jdbc.TxQueryRunner;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.SQLException;

/**
 * User持久层
 *
 * @author LENOVO
 *
 */
public class UserDao {

    private final QueryRunner qr = new TxQueryRunner();

    /**
     * 按用户名查询
     */
    public User findByUsername(String username) {
        try {
            String sql = "select * from tb_user where username=?";
            return qr.query(sql, new BeanHandler<>(User.class), username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 按用户名查询
     */
    public User findByEmail(String email) {
        try {
            String sql = "select * from tb_user where username=?";
            return qr.query(sql, new BeanHandler<>(User.class), email);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 插入User
     */
    public void add(User user) {
        try {
            String sql = "insert into tb_user values(?,?,?,?,?,?)";
            Object[] params = {user.getUid(), user.getUsername(), user.getPassword(), user.getEmail(), user.getCode(),
                    user.isState()};
            qr.update(sql, params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 按激活码查询
     */
    public User findByCode(String code) {
        try {
            String sql = "select * from tb_user where code=?";
            return qr.query(sql, new BeanHandler<>(User.class), code);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改指定用户的指定状态
     */
    public void updateSatate(String uid, boolean state) {
        try {
            String sql = "update tb_user set state=? where uid=?";
            qr.update(sql, state, uid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void change(String username, String password) {
        try {
            String sql = "update tb_user set password=? where username=?";
            qr.update(sql, password, username);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
